package utils

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

// 自定义验证
func InitValidator() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		err := v.RegisterValidation("numStr", numStr)
		if err != nil {
			fmt.Println("success") // 就打印出来吧
		}
	}
}

// 自定义验证规则断言
func numStr(fl validator.FieldLevel) bool {
	if date, ok := fl.Field().Interface().(string); ok {
		for i := 0; i < len(date)-1; i++ {
			if !(date[i] >= '0' && date[i] <= '9') {
				return false
			}
		}
		if (date[len(date)-1] >= '0' && date[len(date)-1] <= '9') || date[len(date)-1] == 'x' {
			return true
		}
	}
	return false
}
